package com.taichuan.selfcheck.ui.fragment;

import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.taichuan.keysupport.Key;
import com.taichuan.keysupport.view.TcKeySupportRecyclerView;
import com.taichuan.keysupport.view.TcLinearLayoutManager;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.entity.file.FileInfo;
import com.taichuan.selfcheck.mvp.presenter.FileListPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.EmptyInterface;
import com.taichuan.selfcheck.mvp.viewinterface.FileListInterface;
import com.taichuan.selfcheck.ui.adapter.FileListAdapter;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.tcutils.taichuan.SystemUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2021/12/25
 */
public class FileListFragment extends AppBaseFragment<FileListInterface, FileListPresenter> implements FileListInterface {
    private static final String TAG = FileListFragment.class.getSimpleName();

    private static final String PARAM_KEY_TITTLE = "file_list_tittle";
    private static final String PARAM_KEY_DIR_PATH = "file_list_dir_path";

    @BindView(R.id.file_list_tv_tip)
    TextView tipTv;
    @BindView(R.id.file_list_recyclerView)
    TcKeySupportRecyclerView fileListRecyclerView;
    @BindView(R.id.btn_file_list_back)
    Button backBtn;

    private String tittle;
    private String dirPath;
    private FileListAdapter fileListAdapter;

    private AlertDialog confirmDialog;

    @Override
    protected void getBundleValues(Bundle bundle) {
        if (bundle != null) {
            tittle = bundle.getString(PARAM_KEY_TITTLE);
            dirPath = bundle.getString(PARAM_KEY_DIR_PATH);
        }
    }

    /**
     * 定义一个方法用于供外部组件启动Activity时传入携带参数
     *
     * @param tittle  标题
     * @param dirPath
     */
    public static Bundle setBundleValue(String tittle, String dirPath) {
        Bundle bundle = new Bundle();
        bundle.putString(PARAM_KEY_TITTLE, tittle);
        bundle.putString(PARAM_KEY_DIR_PATH, dirPath);
        return bundle;
    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_file_list;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        Log.e(TAG, "initView: 当前访问的文件路径为： " + dirPath + " 设置的标题为： " + tittle);

        if (!SystemUtils.isTouchDevice()){
            tipTv.setVisibility(View.VISIBLE);
        }else {
            tipTv.setVisibility(View.GONE);
        }

        fileListAdapter = new FileListAdapter(itemClickListener);
        fileListRecyclerView.setFocusable(false);
        fileListRecyclerView.setItemAnimator(null);
        fileListRecyclerView.setLayoutManager(new TcLinearLayoutManager(getActivity()));
        fileListRecyclerView.setSelectedItemOffset(90, 90);
        fileListRecyclerView.setAdapter(fileListAdapter);
        //触摸版设备的RecyclerView的item点击事件
        fileListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FileInfo item = (FileInfo) adapter.getItem(position);
                doOnItemClick(item);
            }
        });

        //拉取文件数据
        mPresenter.loadFileList(dirPath,true,false);
    }

    /**
     * 按键版设备的RecyclerView点击事件
     */
    private FileListAdapter.OnItemClickListener itemClickListener = new FileListAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position, FileInfo item) {
            if (item != null){
                doOnItemClick(item);
            }
        }
    };

    /**
     * 定义一个方法用于执行RecyclerView的item点击事件
     * @param item
     */
    private void doOnItemClick(FileInfo item) {
        Log.e(TAG, "onItemClick: 选择的为： " + item);
        //根据当前点击的File信息是否为文件夹决定如何执行
        if (!item.isDirectory()) {        //为文件
            //如果该文件为图片文件，则打开PhotoView进行查看
            PhotoViewFragment photoViewFragment = new PhotoViewFragment();
            photoViewFragment.setArguments(PhotoViewFragment.setBundleValue(item));
            getActivityBaseFragmentManager().replace(photoViewFragment);


//            startActivity(TextFileBrowseActivity.class, TextFileBrowseActivity.setBundleValue(item));
        }else {                         //文件夹，再次遍历
            mPresenter.loadFileList(item.getFilePath(),false,false);
        }
    }

    @Override
    public void refreshFileList(List<FileInfo> fileInfoList) {
        //将数据设置给Adapter
        fileListAdapter.setNewData(fileInfoList);
    }

    @Override
    public void refreshTittle() {

    }

    @OnClick({R.id.btn_file_list_back,R.id.btn_clear_file})
    @Override
    public void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()){
            case R.id.btn_file_list_back:{
                //尝试返回上一层级
                boolean isRootLevel = mPresenter.backLastPathLevel();
                if (isRootLevel){       //当前已为根目录层级，直接返回
                    operateFragmentManagerBack();
                }
                break;
            }
            case R.id.btn_clear_file:{
                //开启二次确认框确认是否执行删除
                openConfirmDialogToDeleteDirFile();
                break;
            }
        }
    }

    private void openConfirmDialogToDeleteDirFile() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.btn_delete_file)
                .setMessage("即将删除摄像头拍照测试文件夹中的所有拍照数据，请确认")
                .setPositiveButton(R.string.sure, (dialog, which) -> {
                    //显示进度条
                    showLoading();
                    //执行删除
                    boolean isSuccess = mPresenter.deleteAllFileByOpenPath();

                    //隐藏进度条
                    hideLoading();

                    //拉取文件数据
                    mPresenter.loadFileList(dirPath,true,false);

                    dialog.dismiss();
                    confirmDialog = null;
                })
                .setNegativeButton(R.string.cancel, (dialog, which) -> {
                    dialog.dismiss();
                    confirmDialog = null;
                });
        confirmDialog = builder.create();
        confirmDialog.show();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == Key.Convert.KEYCODE_XING) { //返回
            //尝试返回上一层级
            boolean isRootLevel = mPresenter.backLastPathLevel();
            if (isRootLevel){       //当前已为根目录层级，直接返回
                operateFragmentManagerBack();
            }
            return true;
        }else if (event.getKeyCode() == Key.Convert.KEYCODE_LONG_XING){     //长按*键，强制返回，无论当前目录层级
            operateFragmentManagerBack();
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    protected FileListPresenter createPresenter() {
        return new FileListPresenter();
    }

    @Override
    protected boolean isAllowAutoFinishFragment() {
        return false;
    }

    @Override
    public void doOnAutoFinishFragment() {
        operateFragmentManagerBack();
    }
}
